package com.duofan.gmall.ware.service.impl;

import com.duofan.gmall.common.constant.WareConstant;
import com.duofan.gmall.ware.entity.PurchaseDetailEntity;
import com.duofan.gmall.ware.entity.WareSkuEntity;
import com.duofan.gmall.ware.service.PurchaseDetailService;
import com.duofan.gmall.ware.service.WareSkuService;
import com.duofan.gmall.ware.vo.MergeVo;
import com.duofan.gmall.ware.vo.PurchaseDoneVo;
import com.duofan.gmall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duofan.gmall.common.utils.PageUtils;
import com.duofan.gmall.common.utils.Query;

import com.duofan.gmall.ware.dao.PurchaseDao;
import com.duofan.gmall.ware.entity.PurchaseEntity;
import com.duofan.gmall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    PurchaseDetailService purchaseDetailService;
    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();

        // 如果没有选择采购单则新建采购单
        if(purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatus.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        // TODO 确认采购单状态是0和1才能合并

        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> detailEntities = items.stream().map(e -> {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(e);
            detailEntity.setPurchaseId(finalPurchaseId);
            detailEntity.setStatus(WareConstant.PurchaseStatus.ASSIGNED.getCode());
            return detailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(detailEntities);

        // 更新采购单修改时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    @Transactional
    public void received(List<Long> ids) {
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> {
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(e -> {
            // 确认当前采购单是新建或已分配状态
            if (e.getStatus() == WareConstant.PurchaseStatus.CREATED.getCode() ||
                    e.getStatus() == WareConstant.PurchaseStatus.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        }).map(e -> {
            // 改变采购单的状态
            e.setStatus(WareConstant.PurchaseStatus.RECEIVE.getCode());
            e.setUpdateTime(new Date());
            return e;
        }).collect(Collectors.toList());
        this.updateBatchById(purchaseEntities);

        // 改变采购单所有采购项的状态
        purchaseEntities.forEach(e -> {
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.listDetailByPurchaseId(e.getId());
            List<PurchaseDetailEntity> detailEntitiesUpdate = detailEntities.stream().map(ee -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(ee.getId());
                detailEntity.setStatus(WareConstant.PurchaseDetailStatus.BUYING.getCode());
                return detailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntitiesUpdate);
        });
    }

    @Override
    @Transactional
    public void done(PurchaseDoneVo doneVo) {
        Long id = doneVo.getId();

        // 改变采购项状态
        boolean flag = true;
        List<PurchaseDetailEntity> detailEntities = new ArrayList<>();
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        for(PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if(item.getStatus() == WareConstant.PurchaseDetailStatus.HAS_ERROR.getCode()) {
                // 有可能实际采购8,需求10
                flag = false;
            } else {
                // 入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
            detailEntity.setStatus(item.getStatus());
            detailEntity.setId(item.getItemId());
            detailEntities.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(detailEntities);

        // 改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatus.FINISH.getCode() :
                WareConstant.PurchaseStatus.HAS_ERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

}